class H5ApiServerClient {
    static get(url, params = {}, timeoutMs = 10000) {
        function jsonToUrlParam(json) {
            return Object.keys(json).map(key => key + '=' + json[key]).join('&');
        }
        return new Promise((resolve, reject) => {
            const iframe = document.createElement('iframe');
            iframe.style.display = 'none';
            iframe.src = (params.length == 0) ? url : (url + "?" + jsonToUrlParam(params));
            let timeout = false;
            const timer = setTimeout(() => {
                timeout = true;
                document.body.removeChild(iframe);
                reject(new Error('H5Api request failed. Timeout exceeded.'));
            }, timeoutMs);
            iframe.onload = function () {
                const iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
                const checkContent = () => {
                    const iframeBodyHTML = iframeDoc.body.innerHTML;
                    if (iframeBodyHTML.startsWith('H5ApiServerResult=')) {
                        clearTimeout(timer);
                        document.body.removeChild(iframe);
                        resolve(iframeBodyHTML.replace("H5ApiServerResult=", ""));
                    } else {
                        if (timeout) return;
                        setTimeout(checkContent, 100);
                    }
                };
                checkContent();
            };
            document.body.appendChild(iframe);
        });
    }

    static post(url, params = {}, timeoutMs = 5000) {
        return new Promise((resolve, reject) => {
            const iframe = document.createElement('iframe');
            iframe.style.display = 'none';
            iframe.src = url;
            let timeout = false;
            const timer = setTimeout(() => {
                timeout = true;
                document.body.removeChild(iframe);
                reject(new Error('H5Api request failed. Timeout exceeded.'));
            }, timeoutMs);
            iframe.onload = () => {
                const iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
                iframeDoc.postMessage(JSON.stringify(params), "*");
                const checkContent = () => {
                    const iframeBodyHTML = iframeDoc.body.innerHTML;
                    if (iframeBodyHTML.startsWith('H5ApiServerResult=')) {
                        clearTimeout(timer);
                        document.body.removeChild(iframe);
                        resolve(iframeBodyHTML.replace("H5ApiServerResult=", ""));
                    } else {
                        if (timeout) return;
                        setTimeout(checkContent, 100);
                    }
                };
                checkContent();
            };
            document.body.appendChild(iframe);
        });
    }
}
